var shindig = shindig || {};
shindig.samplecontainer = {};

(function(){

  /**
   * Private Variables
  */

  var parentUrl = document.location.href;
  var baseUrl = parentUrl.substring(0, parentUrl.indexOf('index.html')) || "http://localhost:8080/";
  var socialDataPath = document.location.protocol + "//" + document.location.host + "/social/rest/samplecontainer/";
  var gadgetUrl =  baseUrl + 'gadgets/friends.xml';
  var viewerId = "john.doe";
  var ownerId = "john.doe";
  var current_view = "default";

  /**
   * Private Functions
   */

  function generateSecureToken() {
    // TODO: Use a less silly mechanism of mapping a gadget URL to an appid
    var appId = 0;
    for (var i = 0; i < gadgetUrl.length; i++) {
      appId += gadgetUrl.charCodeAt(i);
    }
    var fields = [ownerId, viewerId, appId, "shindig", gadgetUrl, "0", "default"];
    for (var i = 0; i < fields.length; i++) {
      // escape each field individually, for metachars in URL
      fields[i] = escape(fields[i]);
    }
    return fields.join(":");
  }

  SampleContainerGadget = function(opt_params) {
    gadgets.IfrGadget.call(this, opt_params);
  };

  SampleContainerGadget.inherits(gadgets.IfrGadget);

  SampleContainerGadget.prototype.getAdditionalParams = function() {};

  gadgets.container.gadgetClass = SampleContainerGadget;
  
  function sendRequestToServer(url, method, opt_postParams, opt_callback, opt_excludeSecurityToken) {
    // TODO: Should re-use the jsoncontainer code somehow
    opt_postParams = opt_postParams || {};

    var makeRequestParams = {
      "CONTENT_TYPE" : "JSON",
      "METHOD" : method,
      "POST_DATA" : opt_postParams};

    if (!opt_excludeSecurityToken) {
      url = socialDataPath + url + "?st=" + gadget.secureToken;
    }

    gadgets.io.makeNonProxiedRequest(url,
      function(data) {
        data = data.data;
        if (opt_callback) {
            opt_callback(data);
        }
      },
      makeRequestParams
    );
  };

  function generateGadgets(metadata) {
    // TODO: The gadget.js file should really have a clearGadgets method
    gadgets.container.view_ = current_view;
    gadgets.container.gadgets_ = {};
    for (var i = 0; i < metadata.gadgets.length; i++) {
      gadget = gadgets.container.createGadget(
          {'specUrl': metadata.gadgets[i].url, 'title': metadata.gadgets[i].title});
      // Shindigs rpc code uses direct javascript calls when running on the same domain
      // to simulate cross-domain when running sample container we replace 
      // 'localhost' with '127.0.0.1' 
      var iframeBaseUrl = baseUrl.replace("localhost", "127.0.0.1") + '../../gadgets/';

      gadget.setServerBase(iframeBaseUrl);
      gadget.secureToken = escape(generateSecureToken());
      gadgets.container.addGadget(gadget);
    }

    gadgets.container.layoutManager.setGadgetChromeIds(['gadget-chrome']);
    gadgets.container.renderGadgets();
  };

  function refreshGadgets(metadata) {
    // TODO: The gadget.js file should really have a getGadgets method
    for (var gadget in gadgets.container.gadgets_) {
      var newtitle = metadata.gadgets[0].title;
      var specUrl = metadata.gadgets[0].url;
      gadgets.container.gadgets_[gadget].title = newtitle;
      gadgets.container.gadgets_[gadget].specUrl = specUrl;
      gadgets.container.gadgets_[gadget].secureToken = escape(generateSecureToken());
    }
    gadgets.container.renderGadgets();
  }

  function requestGadgetMetaData(opt_callback) {
    var request = {
      context: {
        country: "default",
        language: "default",
        view: "home",
        container: "default"
      },
      gadgets: [{
        url: gadgetUrl,
        moduleId: 1
      }]
    };

    sendRequestToServer("/gadgets/metadata", "POST", gadgets.json.stringify(request), opt_callback, true);
  }

  shindig.samplecontainer.initGadget = function() {
    requestGadgetMetaData(generateGadgets);
  };
  
  osapi.messages = {};
  osapi.messages.requestSend = function(request, callback) {
    alert("osapi.messages.requestSend called");
    callback({});
  };

  osapi.requestShareApp = function(request, callback) {
    alert("osapi.requestShareApp called");
    callback({});
  };

  osapi.requestPermission = function(request, callback) {
    alert("osapi.requestPermission called");
    callback({});
  };

})();
